//
//  RealTimeHistoryController.m
//  CoolTennisBall
//
//  Created by Coollang on 16/7/29.
//  Copyright © 2016年 CoolLang. All rights reserved.
//

#import "RealTimeHistoryController.h"
#import "UIColor+Extension.h"
#import "RealHistoryCell.h"
#import "RealTimeHBReportController.h"
#import "RealTimeFQReportController.h"
#import "RealTimeTrainModel.h"
#import "NSDate+FormateString.h"


//#import "SportDetailReportModel.h"

static NSString *reuseIdentifier = @"RealHistoryCell";

@interface RealTimeHistoryController ()<UITableViewDelegate, UITableViewDataSource, LBCalendarDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (strong, nonatomic)UIView *titleView;

/** 有训练的对应天字符串数组 */
//@property (nonatomic, strong) NSArray *trainDays;

/** key训练的天 value: 那一天训练的数据 */
@property (nonatomic, strong) NSDictionary *dayWithTrainDict;

@property (nonatomic, strong) NSMutableArray *dataSource;
//@property (strong, nonatomic) SportDetailReportModel *detailReportModel;
@end

@implementation RealTimeHistoryController {
    YFLanguage _currentLanguage;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _currentLanguage = [NSBundle currentLangeuage];
    
    [self createCalendarheaderView];
    [self createBGScrollview];
    [self CreatCalendarManagerAndCaldarView];
    
    [self createTableView];
    [self dispossData];
    [self firstEnter];

}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]  removeObserver:self];
}

#pragma mark - 设置导航栏
- (void)createCustomNavBarBt {
    
    self.title = NSLocalizedString(@"Training Record", @"历史记录");
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"sport_icon_blackbackArrow"] style:UIBarButtonItemStylePlain target:self action:@selector(backBtTap)];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
                                              initWithTitle:NSLocalizedString(@"Recently", nil)
                                              style:UIBarButtonItemStylePlain
                                              target:self
                                              action:@selector(didGoRecentyTouch)];
}
- (void)backBtTap {
    [self.navigationController popViewControllerAnimated:YES];
}
// 最近
- (void)didGoRecentyTouch {
    
    if (self.dayWithTrainDict.allKeys.count > 0 && self.dayWithTrainDict.allValues.count > 0) {

       RealTimeTrainModel *model = [self.dayWithTrainDict[[self sortdayWithTrainDicAllKey].lastObject] lastObject];
       
        [self.calendar setCurrentDate: [model date]];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"kLBCalendarDaySelected" object:[model date]];
        [self updateTabelViewDataSourceWithDay:[[model date] formateYearMonthDay]];
       
    }else {
        [self.calendar setCurrentDate:[NSDate date]];
    }
 
}

- (void)createCalendarheaderView {
    
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kYFScreenWidth, 67)];
    titleView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:titleView];
    
    UIButton *titleButton = [[UIButton alloc] initWithFrame:CGRectMake(kYFScreenWidth * 0.5 - 50, 6, 100, 30)];
    
    [titleButton setTitleColor:[UIColor colorWithHex:0x7b7a80 alpha:0.8] forState:UIControlStateNormal];
    titleButton.titleLabel.font = [UIFont boldSystemFontOfSize:15];
    [titleView addSubview:titleButton];
    self.SelectionMonthBt = titleButton;
    
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(kYFScreenWidth * 0.5 - 118, 6, 30, 30)];
    [leftButton setImage:[UIImage imageNamed:@"icon_previous"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(setPreviousMonthDate) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:leftButton];
    
    UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(kYFScreenWidth * 0.5 + 88, 6, 30, 30)];
    [rightButton setImage:[UIImage imageNamed:@"icon_next"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(setNextMonthDate) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:rightButton];
    
    self.titleView = titleView;
    
    NSArray *array = nil;
    
    if (_currentLanguage == kLanguageChineseSimple) {
        array = @[@"日",@"一",@"二",@"三",@"四",@"五",@"六"];
    }else {
        array = @[NSLocalizedString(@"Sun", nil),
                  NSLocalizedString(@"Mon", nil),
                  NSLocalizedString(@"Tues", nil),
                  NSLocalizedString(@"Wed", nil),
                  NSLocalizedString(@"Thur", nil),
                  NSLocalizedString(@"Fri", nil),
                  NSLocalizedString(@"Sat", nil)];
    }

    CGFloat labelY  = CGRectGetMaxY(self.SelectionMonthBt.frame) + 8;
    CGFloat labelW = self.view.frame.size.width / 7;
    CGFloat labelH = 20;
    for (int i = 0; i < 7; i++) {
        UILabel *week = [[UILabel alloc] init];
        week.text     = array[i];
        week.textColor = [UIColor colorWithHex:0x7b7a80 alpha:0.7];
        week.font = MYFONT(11);
        week.frame    = CGRectMake(labelW * i, labelY, labelW, labelH);
        week.textAlignment   = NSTextAlignmentCenter;
        week.backgroundColor = [UIColor clearColor];
        [self.titleView addSubview:week];
    }
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 66.5, kYFScreenWidth, 0.5)];
    
    lineView.backgroundColor = kBackgroundColorDeep;
    lineView.alpha = 0.5;
    [self.titleView addSubview:lineView];
    
    
}
- (void)updateym:(NSNotification *)notification{
    [_SelectionMonthBt  setTitle:[notification object] forState:UIControlStateNormal];
}

// 上一个月
- (void)setPreviousMonthDate {
    [self.calendar loadPreviousMonth];
}
// 下一个月
- (void)setNextMonthDate {
    [self.calendar loadNextMonth];
}
#pragma mark - 初始化日历管理器和界面
- (void)CreatCalendarManagerAndCaldarView {
    calendarContentView = [[LBCalendarContentView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 240)];
    [BGScrollview addSubview:calendarContentView];
    
    self.calendar = [LBCalendar new];
    self.calendar.calendarAppearance.calendar.firstWeekday = 1; // Sunday == 1, Saturday == 7
    self.calendar.calendarAppearance.dayRectangularRatio = 9. / 10.;
    
    [self.calendar setContentView:calendarContentView];
    [self.calendar setDataSource:self];
    
    [self createCustomNavBarBt];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateym:) name:@"currentYearMonth" object:nil];
    
    [self.calendar setCurrentDate:self.calendar.currentDate];
}

- (void)firstEnter {
    [self didGoRecentyTouch];
    if (self.realTimeTrainHistoryData.count > 0) {
        
        RealTimeTrainModel *model = [self.dayWithTrainDict[[self sortdayWithTrainDicAllKey].lastObject] lastObject];
        
        [self calendarDidDateSelected:self.calendar date:[model date]];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"kLBCalendarDaySelected" object:[model date]];
    }
}


- (void)createBGScrollview{
    
    BGScrollview = [[UIScrollView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.titleView.frame), self.view.frame.size.width, 240)];
    BGScrollview.contentSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height);
    
    BGScrollview.pagingEnabled = YES;
    BGScrollview.showsVerticalScrollIndicator = NO;
    BGScrollview.delegate = self;
    BGScrollview.scrollEnabled = NO;
    BGScrollview.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:BGScrollview];
}

#pragma mark - 处理所有的实时训练数据
- (void)dispossData {
    
    __block RealTimeTrainModel *temp = nil;
    
    __block NSMutableArray *tempArrm = [NSMutableArray array];
    NSMutableArray *arrM = [NSMutableArray array];
    
//    NSLog(@"%@",weakSelf.realTimeTrainHistoryData);
    
    [self.realTimeTrainHistoryData enumerateObjectsUsingBlock:^(RealTimeTrainModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        // 是同一天
        if ([[obj yearAndMonthAndDay]isEqualToString:[temp yearAndMonthAndDay]]) {
            [tempArrm addObject:obj];
            
        }else if(![[obj yearAndMonthAndDay]isEqualToString:[temp yearAndMonthAndDay]]){
            
            temp = obj;
            
            if (tempArrm.count > 0) {
                tempArrm = nil;
                tempArrm = [NSMutableArray array];
            }
            [tempArrm addObject:obj];
            [arrM addObject:tempArrm];
            
        }
    }];
    
    
    NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
    
    [arrM enumerateObjectsUsingBlock:^(NSArray * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        RealTimeTrainModel *model = obj.firstObject;
        
        [dictM setObject:obj forKey:[model yearAndMonthAndDay]];
        
    }];
//    NSLog(@"%@",dictM.allKeys);
    self.dayWithTrainDict = dictM.copy;
}

// 按时间先后循序排序
- (NSArray *)sortdayWithTrainDicAllKey {
     return [self.dayWithTrainDict.allKeys sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:nil ascending:YES]]];
}

#pragma mark - LBCalendarDataSource
- (BOOL)calendarHaveEvent:(LBCalendar *)calendar date:(NSDate *)date {
    
    if ([self.dayWithTrainDict.allKeys containsObject:[date formateYearMonthDay]]) {
        return YES;
    }else {
        return NO;
    }
   
}

- (void)calendarDidDateSelected:(LBCalendar *)calendar date:(NSDate *)date
{
    NSLog(@"Date: %@", date);
    [[NSNotificationCenter defaultCenter] postNotificationName:@"DaySelected" object:date];
    
    if ([self.dayWithTrainDict.allKeys containsObject:[date formateYearMonthDay]]) {
        
        [self updateTabelViewDataSourceWithDay:[date formateYearMonthDay]];
    }
}

- (void)updateTabelViewDataSourceWithDay:(NSString *)dayString {
    
    self.dataSource = self.dayWithTrainDict[dayString];
    
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
}



#pragma mark - tableView的初始化
- (void)createTableView {
    // 创建tableView
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(BGScrollview.frame) + 7, kYFScreenWidth, kYFScreenHeight - (CGRectGetMaxY(BGScrollview.frame) + 7)) style:UITableViewStylePlain];
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    [self.view addSubview:self.tableView];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"RealHistoryCell" bundle:nil] forCellReuseIdentifier:reuseIdentifier];
    
    self.view.backgroundColor = [UIColor colorWithHex:0xf7f7f7 alpha:1.0];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kYFScreenWidth, kAutoHei(90))];
    
}

#pragma mark - UITableViewDelegate & UITableViewDateSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    RealHistoryCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier forIndexPath:indexPath];
    
    cell.trainModel = self.dataSource[indexPath.row];
    
    return cell;
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return kAutoHei(67);
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    RealTimeTrainModel *trainModel = self.dataSource[indexPath.row];

    if (trainModel.trainTyep == RealTimeTrainHB) {
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"RealTimeTrainReport" bundle:nil];
        
        RealTimeHBReportController *HBreportVc = [sb instantiateViewControllerWithIdentifier:@"RealTimeHBReportController"];
        HBreportVc.trainModel = trainModel;
        [self.navigationController pushViewController:HBreportVc animated:YES];
    }else if (trainModel.trainTyep == RealTimeTrainFQ){
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"RealTimeTrainReport" bundle:nil];
        
        RealTimeFQReportController *FQreportVc = [sb instantiateViewControllerWithIdentifier:@"RealTimeFQReportController"];
        FQreportVc.trainModel = trainModel;
        
        [self.navigationController pushViewController:FQreportVc animated:YES];
    }
    
}


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    __weak typeof(self) weakSelf = self;
    
    // 首先改变model
    RealTimeTrainModel *model = self.dataSource[indexPath.row];
    
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:NSLocalizedString(@"Delete", nil) handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {

        NSString *tipstr2 = nil;
        if (_currentLanguage == kLanguageChineseSimple) {
            tipstr2 = [NSString stringWithFormat: @"确定要删除%@的训练记录吗？",[model hourAndMinute]];
        }else if (_currentLanguage == kLanguageFrennch){
            tipstr2 = [NSString stringWithFormat:@"Confirm to delete the training record of %@?",[model hourAndMinute]];
        }else {
            tipstr2 = [NSString stringWithFormat:@"Confirm to delete the training record of %@?",[model hourAndMinute]];
        }
        
//       弹框
        FUIAlertView *alertView = [[FUIAlertView alloc] initWithTitle:NSLocalizedString(@"Reminder", nil) message:tipstr2 delegate:nil cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Ok", nil), nil];
        
        [alertView customizeAppearance];
        
        alertView.onOkAction = ^{
            
            if (model.ID != nil) {
                YFTrainingApi *deleteApi = [YFTrainingApi deleteTrainRealTimeHistortDataWithTrainType:model.trainTyep trainID:model.ID];
                [[YFNetworkingService sharedInstance] sendRequest:deleteApi callback:^(BOOL success, id result, NSError *error) {
                    if (success) {
                        [weakSelf deleteDataAndReloadTabelViewWith:indexPath model:model];
                    }else {
                        [MBProgressHUD showTextHUDWithMessage:NSLocalizedString(@"RealTime.Delete failure", nil) inView:self.view];
                    }
                }];
            }else {
                [weakSelf deleteDataAndReloadTabelViewWith:indexPath model:model];
            }
        };
        
        alertView.onCancelAction = ^{
            [weakSelf.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
        };
        
        [alertView show];

    }];

    
    return @[deleteAction];
}


- (void)deleteDataAndReloadTabelViewWith:(NSIndexPath *)indexPath model:(RealTimeTrainModel *) model {
    
    [self.realTimeTrainHistoryData removeObject:model];
    [self.dataSource removeObjectAtIndex:indexPath.row];
    
    if (self.saveRealTimeTrainModel != nil) {
        self.saveRealTimeTrainModel(self.realTimeTrainHistoryData);
    }
    
    if (self.dataSource.count == 0 ) {
        
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [self dispossData];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            if (self.realTimeTrainHistoryData.count > 0) {
                [self firstEnter];
            }else {
                // 接着刷新view
                [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
                [self didGoRecentyTouch];
            }
        });
        
    }else {
        // 接着刷新view
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

@end

/*
 [weakSelf.realTimeTrainHistoryData removeObject:model];
 [weakSelf.dataSource removeObjectAtIndex:indexPath.row];
 
 if (weakSelf.saveRealTimeTrainModel != nil) {
 weakSelf.saveRealTimeTrainModel(weakSelf.realTimeTrainHistoryData);
 }
 
 if (weakSelf.dataSource.count == 0 ) {
 
 [MBProgressHUD showHUDAddedTo:weakSelf.view animated:YES];
 [weakSelf dispossData];
 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
 [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
 
 if (weakSelf.realTimeTrainHistoryData.count > 0) {
 [weakSelf firstEnter];
 }else {
 // 接着刷新view
 [weakSelf.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
 [weakSelf didGoRecentyTouch];
 }
 });
 
 }else {
 // 接着刷新view
 [weakSelf.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
 }
 */

